﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MovementController : MonoBehaviour
{
    /// <summary>
    /// 角色的移动速度
    /// </summary>
    public float movementSpeed = 3.0f;
    /// <summary>
    /// 角色移动的位置
    /// </summary>
    Vector2 movement = new Vector2();
    /// <summary>
    /// 动画绘制者
    /// </summary>
    Animator animator;
    /// <summary>
    /// 动画状态
    /// </summary>
    string animationState = "AnimationState";
    /// <summary>
    /// 刚体
    /// </summary>
    Rigidbody2D rb2D;

    /// <summary>
    /// 角色状态
    /// </summary>
    enum CharStates
    {
        walkEast = 1,
        walkSouth = 2,
        walkWest = 3,
        walkNorth = 4,
        idleSouth = 5
    }

    // Start is called before the first frame update
    void Start()
    {
        animator = GetComponent<Animator>();
        rb2D = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        UpdateState();
    }

    /// <summary>
    /// 以固定的时间间隔调用
    /// </summary>
    void FixedUpdate()
    {
        MoveCharacter();
    }

    /// <summary>
    /// 移动角色
    /// </summary>
    private void MoveCharacter()
    {
        movement.x = Input.GetAxisRaw("Horizontal");
        movement.y = Input.GetAxisRaw("Vertical");
        movement.Normalize();
        rb2D.velocity = movement * movementSpeed;
    }


    private void UpdateState()
    {
        if (movement.x > 0)
            animator.SetInteger(animationState, (int)CharStates.walkEast);
        else if (movement.x < 0)
            animator.SetInteger(animationState, (int)CharStates.walkWest);
        else if (movement.y > 0)
            animator.SetInteger(animationState, (int)CharStates.walkNorth);
        else if (movement.y < 0)
            animator.SetInteger(animationState, (int)CharStates.walkSouth);
        else
            animator.SetInteger(animationState, (int)CharStates.idleSouth);
    }
}
